package com.cssw.fyzb.busi.api.video;

import com.cssw.fyzb.core.exception.BizException;
import com.cssw.fyzb.core.model.vo.video.VideoHotDefVo;
import com.cssw.fyzb.busi.service.video.VideoService;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.*;
import com.ydn.simplelock.SimpleLock;
import com.ydn.simplelock.SimpleLockFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 购买热门信息
 *
 * @author YangYiQun
 */
@Function(description = "购买热门信息", parameters = {
        @Parameter(name = "userId", type = Type.Integer, description = "用户标识", required = true),
        @Parameter(name = "videoId", type = Type.Integer, description = "视频标识", required = true),
        @Parameter(name = "hotId", type = Type.Integer, description = "热门标识", required = true),
        @Parameter(name = "pwd", type = Type.Integer, description = "交易密码", required = true)
})
@Component
public class BuyVideoHot implements Action {

    @Autowired
    private VideoService videoService;

    @Autowired
    private SimpleLockFactory simpleLockFactory;

    private static final Logger logger = LoggerFactory.getLogger(BuyVideoHot.class);

    @Override
    public Response execute(Request request) throws Exception {
        Long userId = request.getLong("userId");
        Long videoId = request.getLong("videoId");
        Long hotId = request.getLong("hotId");
        String pwd = request.getString("pwd");
        SimpleLock lock = simpleLockFactory.getLock("USER_" + userId);
        try {
            lock.acquire();

            videoService.buyHot(userId, videoId, hotId, pwd);
            return Response.success();
        } catch (Exception e) {
            if (e instanceof BizException) {
                BizException be = (BizException) e;
                return Response.fail(be.getErrMsg(), be.getErrCode());
            }
            logger.info("", e);
            return Response.fail("操作异常");
        } finally {
            lock.release();
        }
    }

}
